<template>
  <div>
    <van-nav-bar
      title="登录"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form @submit="submitFn">
      <van-field
        v-model="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        required
        label="验证码"
        placeholder="请输入验证码"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :disabled="isDisabled">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  name: 'Login',
  data () {
    return {
      isDisabled: false,
      mobile: '',
      code: '',
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    async submitFn () {
      this.isDisabled = true
      try {
        const res = await login(this.mobile, this.code)
        this.$toast.success('登录成功')
        this.$store.commit('user/setToken', res.data)
        if (this.$route.query.goBack) {
          return this.$router.back()
        }
        // 不能直接跳到首页获取到当前路由跳转地址 如获取不到就跳首页
        const back = this.$route.query.back || '/'
        this.$router.push(back)
      } catch {
        this.$toast.fail('用户名或验证码错误')
      }
      this.isDisabled = false
    }
  }
}
</script>

<style>

</style>
